package heap

import "unicode/utf16"

var internedStrings = map[string]*Object{}

func JString(loader *ClassLoader, goStr string) *Object {
	//若字符串常量池已包含相应字符串，则直接返回
	if internedString, ok := internedStrings[goStr]; ok {
		return internedString
	}
	//将golang中的字符串(utf8格式)转换为java中的字符串(utf16)
	chars := stringToUtf16(goStr)
	jChars := &Object{loader.LoadClass("[C"), chars,nil}
	//创建String对象承载该string值
	jStr := loader.LoadClass("java/lang/String").NewObject()
	jStr.SetRefVar("value", "[C", jChars)
	//将其放入池中
	internedStrings[goStr] = jStr
	return jStr
}

func stringToUtf16(str string) []uint16 {
	rs := []rune(str)       //utf8 -> utf32
	return utf16.Encode(rs) //utf32 -> utf16
}

func GoString(jStr *Object) string {
	charArr := jStr.GetRefVar("value", "[C")
	return utf16ToString(charArr.Chars())
}

func utf16ToString(chars []uint16) string {
	return string(utf16.Decode(chars))
}
